import java.io.*;
import java.net.*;
import java.util.*;

public class ParserThread extends Thread{
	URL objURL;
	Vector<Event> objEvents = new Vector<Event>();
	String cleanBuffeer = null;
	String strBuffer = null;
	String[] titleSplit = null;
	String strBandName;
	ArrayList<String> strEvents = new ArrayList<String>();
	URLsManager objURLsManager;
	EventsManager objEventManager;

	public ParserThread(URL objURL) {
		this.objURL = objURL;
	}

	public ParserThread(URLsManager objURLsManager, EventsManager objEventManager) {
		this.objURLsManager = objURLsManager;
		this.objEventManager = objEventManager;
	}

	public void goParse(URL objURL) throws IOException{
		this.objURL = objURL;
		boolean blnConnector;
		int intCount = 0, intCountMax = 3;
		HttpURLConnection objHUC = null;

		do {
			blnConnector = true;
			try{
				objHUC = (HttpURLConnection)objURL.openConnection();
				/* If unable to connect, retry another (intCount - 1) times */
			} catch (IOException e) {
				if (intCount < intCountMax)
					System.out.println("\n~~~Connection failed for " + objURL.toString() + "!!!~~~\n"
							+ "Retry...\n");
				else {
					System.out.println("\n~~~Connection failed too many times for " + objURL.toString() + "!!!~~~\n"
							+ "Aborted...\n");
				}
				intCount++;
				blnConnector = false;
			}
		} while (!blnConnector && intCount < intCountMax);

		if (blnConnector) {
			if (objHUC.getResponseCode() == HttpURLConnection.HTTP_OK){
				/**/System.out.println(this.getName() + " will now parse \"" + objURL.toString() + "\" data...\n");
				InputStreamReader objInputStream = new InputStreamReader(objHUC.getInputStream());
				BufferedReader objBufferRead = new BufferedReader(objInputStream);

				/* Reading first line */
				strBuffer = objBufferRead.readLine();
				/* Search title's tag */
				while (!strBuffer.contains("<title>")){
					strBuffer = objBufferRead.readLine();
				}
				/* Reading first line after title */
				strBuffer = objBufferRead.readLine();
				/* Parsing title to get band's name */
				titleSplit = strBuffer.split(" ");
				strBuffer = "";
				int i = 0;
				while (!titleSplit[i].equals("su")){
					strBuffer = strBuffer + " " + titleSplit[i];
					i++;
				}
				/* Adding group name to data array */
				strEvents.add(strBuffer.trim());
				strEvents.add(objURL.toString());

				/* Searching tag profile_bandschedule */
				while (((strBuffer = objBufferRead.readLine()) != null) && !strBuffer.contains("id=\"profile_bandschedule\""));
				/* Reading every event and cleaning tag from strings */
				while (((strBuffer = objBufferRead.readLine()) != null) && !strBuffer.contains("</div>")){
					if (strBuffer.contains("<a href=") && !(strBuffer.contains("class=\"whitelink\""))){
						String strHREF=strBuffer.substring(strBuffer.indexOf("href"), strBuffer.indexOf("\">",strBuffer.indexOf("href")));
						strHREF=strHREF.replace("href=\"", "");
						strEvents.add(strHREF);
					}
					if (!strBuffer.contains("Prossimi spettacoli") && !strBuffer.contains("visualizza tutto")
							&& strBuffer.contains("font")){
						cleanBuffeer = strBuffer.replaceAll("<.*?>", "");
						strBuffer = cleanBuffeer.replaceAll("\\&.*\\;", "");
						cleanBuffeer = strBuffer.trim();
						strBuffer = cleanBuffeer;

						strEvents.add(strBuffer);
					}
					if (strEvents.size() == 7){
						strBandName = strEvents.get(0);
						objEventManager.setObjEventsValue(new Event(strEvents));
						strEvents.clear();
						strEvents.add(strBandName);
						strEvents.add(objURL.toString());
					}
				}
				/* He found </div> or null, so clearing ArrayList for safety */
				strEvents.clear();
			}
		}
	}


	public void run(){
		String strURL;
		try {
			while((strURL=objURLsManager.getStrURLsValue())!= null){
				/**/System.out.println(this.getName() + " is now connecting to \"" + strURL + "\" data...\n");/**/
				URL objURL = new URL(strURL); 
				goParse(objURL);
				/**/System.out.println(this.getName() + " parsed \"" + strURL + "\" data.\n");/**/
			}

			/* If read a null, warns Event Manager the thread is ended up */
			objEventManager.tellYouEnded();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}